package com.lyang.mall.rabbit.consumer;

import com.lyang.mall.api.order.constant.OrderConstant;
import com.lyang.mall.api.order.entity.Stock;
import com.lyang.mall.api.order.service.OrderService;
import com.lyang.mall.rabbit.config.RabbitMQConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 创建订单消费者
 */

@Component
public class OrderConsumer {
    private static final Logger logger = LoggerFactory.getLogger(OrderConstant.class);

    @Resource
    private OrderService orderService;

    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME_ORDER)
    public String processMessage(byte[] msg) {
        try{
            System.out.println(Thread.currentThread().getName() + " 接收到来自"+RabbitMQConfig.QUEUE_NAME_ORDER+"队列的消息：" + msg);
            Stock stock = (Stock) SerializationUtils.deserialize(msg);
            //由于创建订单的服务仍是mall-biz-order,这里实现一个折中方式，休眠一分钟，避开秒杀的高峰期
            Thread.currentThread().sleep(60*1000);
            orderService.createStockOrder(stock);
        }catch(Exception e){
            logger.error("消费订单失败",e);
        }
        return null;
    }

}
